<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/store/auth';
import { usePopup } from '@/utils/popup';
import { useLocale } from '@/locale/locale';

const { t } = useLocale();
const authStore = useAuthStore();
const { loginForm } = storeToRefs(authStore);
const { popupRef, open } = usePopup();

function handleOpen() {
  if (authStore.isSent) {
    return;
  }

  if (!authStore.isAgreementAccepted) {
    return uni.showToast({
      title: t('LLKey_readAgree'),
      icon: 'none'
    });
  }

  if (authStore.isPhoneMode) {
    open();
  } else {
    authStore.sendVerificationCode();
  }
}

function handleInputChange(e: AnyObject) {
  authStore.setVerificationCode(e.detail.value);
}

function handleConfirm() {
  if (!authStore.isSent) {
    authStore.sendVerificationCode();
  }
}
</script>

<template>
  <view class="mb-5 input-verification-code">
    <view class="flex items-center">
      <view class="flex-1 mr-1">
        <input :placeholder="t('LLKey_codePlaceholder')" @input="handleInputChange" />
      </view>
      <view
        :style="{
          width: authStore.isSent ? '80rpx' : '160rpx',
          transition: 'width 0.3s ease'
        }"
        class="text-base text-primary font-medium text-right"
        @click="handleOpen"
      >
        <text v-if="authStore.isSent" class="text-fourth">
          {{ `${authStore.retrySeconds}s` }}
        </text>
        <text v-else>{{ t('LLKey_sendCode') }}</text>
      </view>
    </view>
  </view>

  <uni-popup ref="popupRef">
    <uni-popup-dialog
      :cancel-text="t('LLKey_loginCheckModify')"
      :confirm-text="t('LLKey_loginCheckConfirm')"
      :title="t('LLKey_loginCheckTheInformation')"
      show-close
      type="info"
      @confirm="handleConfirm"
    >
      <view class="flex flex-col justify-center items-center">
        <view class="text-lg text-third">
          {{ `${t('LLKey_loginCheckCode')}${loginForm.countryPrefix}(${loginForm.countryName})` }}
        </view>
        <view class="text-lg text-third">
          {{ `${t('LLKey_loginPhone')}: ${loginForm.phoneNumber}` }}
        </view>
      </view>
    </uni-popup-dialog>
  </uni-popup>
</template>

<style lang="scss">
.input-verification-code {
  width: 630rpx;
  height: 100rpx;
  padding: 28rpx 48rpx;
  border-radius: 214rpx;
  background: rgba(0, 0, 0, 0.04);
}
</style>
